<template>
  <div class="login-container">
    <el-form :model="ruleForm" :rules="rules" status-icon ref="ruleForm" label-position="left" label-width="0px"
      class="demo-ruleForm login-page">
      <div class="login_box" v-if="loginType">
        <h3 class="title" align="center">系统登录</h3>
        <el-form-item prop="username">
          <el-input type="text" v-model="ruleForm.username" auto-complete="off" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" v-model="ruleForm.password" auto-complete="off" placeholder="密码"></el-input>
        </el-form-item>
      </div>
      <div class="login_box" v-if="!loginType">
        <h3 class="title" align="center">注册 5BOOKS</h3>
        <el-form-item prop="username">
          <el-input type="text" v-model="ruleForm.username" auto-complete="off" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" v-model="ruleForm.password" auto-complete="off" placeholder="密码"></el-input>
        </el-form-item>
        <el-form-item prop="phone" >
          <el-input type="text" v-model="ruleForm.phone" auto-complete="off" placeholder="手机号" style="width: 220px;"></el-input>
          <span>&nbsp;</span>
          <!-- <el-input type="button" style="width: 100px;" value="发送验证码"></el-input> -->
          <el-button type="success" @click="sendVerifyCode">发送验证码</el-button>
        </el-form-item>
        <el-form-item prop="verifyCode">
          <el-input type="text" v-model="verifyCode" auto-complete="off" placeholder="验证码"></el-input>
        </el-form-item>
      </div>
      <el-form-item style="width:100%;">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-button type="primary" style="width:100%;" @click="handleSubmit">登录</el-button>
            </div>
          </el-col>
          <!--          <el-col :span="12"><div class="grid-content bg-purple">
            <el-button type="info" style="width:100%;" @click="resetForm">重置</el-button>
          </div>
          </el-col> -->
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-button type="info" style="width:100%;" @click="signUp">注册</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  export default {
    name: "login",
    data() {
      return {
        USER_ID: '',
        ruleForm: {
          username: 'DAMN4374',
          password: '',
          phone: ''

        },
        rules: {
          username: [
            {
              required: true,
              message: '请输入用户名',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 20,
              message: '长度在 3 到 20 个字符',
              trigger: 'blur'
            }
          ],
          password: [
            {
              required: true,
              message: '请输入密码',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 20,
              message: '长度在 3 到 20 个字符',
              trigger: 'blur'
            }
          ],
          phone: [
            {
              required: true,
              message: '请输入手机号',
              trigger: 'blur'
            },
            {
              min: 11,
              max: 11,
              message: '请输入正确的手机号',
              trigger: 'blur'
            }
          ]
        },
        loginType: true,
        verifyInfo: {
          phone: '15287979549'
        },
        verifyCode: '',
        verifyCodeBack: '',
        signInNum: '1',
        signUpNum: '0'
      }
    },
    methods: {
      resetForm() {
        // 获取当前vue提交对象
        this.ruleForm = {}
      },
      handleSubmit() {
        if(this.signInNum == '0'){
          this.loginType = true
          this.signInNum = '1'
          this.signUpNum = '0'
          this.resetForm()
        }else{
          this.loginType = true
          this.signInNum = '1'
          this.signUpNum = '0'
          this.$refs.ruleForm.validate(async validate => {
            if (!validate) return;
            const {
              data: result
            } = await this.$http.post('/user/login', this.ruleForm);
            console.log(result.data)
            if (result.status != 200) return this.$message.error('用户名或者密码错误!');
            else this.$message.success("登录成功!")
            // this.$bus.USER_ID=token
            window.sessionStorage.setItem('userId', result.data.id)
            window.sessionStorage.setItem('userName', result.data.username)
            this.$store.commit('refreshUserId', result.data.id) //更新vuex中保存的用户变量
            this.$store.commit('refreshUserName', result.data.username)
            this.$router.push('/index')
        })
      }},
      async signUp(){
        if(this.signUpNum == '0'){
          this.loginType = false
          this.signUpNum = '1'
          this.signInNum = '0'
          this.resetForm()
        }else{
          this.loginType = false
          this.signUpNum = '1'
          this.signInNum = '0'
          if(this.verifyCode != this.verifyCodeBack){
            return this.$message.error('验证码错误!');
          }else{
            // const {
            //   data: result
            // } = await this.$http.put('/user/signUp', this.ruleForm);
            // if (result.status != 200) return this.$message.error('抱歉，注册失败!');
            // else this.$message.success("注册成功!")

            this.$refs.ruleForm.validate(async validate => {
              if (!validate) return;
              const {
                data: result
              } = await this.$http.put('/user/signUp', this.ruleForm);
              console.log("提交注册信息："+result.status+"----"+this.ruleForm.username)
              if (result.status != 200) return this.$message.error('抱歉，注册失败!');
              else {
                const {data:userRes} = await this.$http.get(`/user/getUserByName/${this.ruleForm.username}`)
                if(userRes.status != 200) return this.$message.error('抱歉，注册失败!')
                this.$message.success("注册成功!")

                let msg = {
                  send: '1',
                  rece: userRes.data.signId,
                  message: "欢迎您，新用户"+this.ruleForm.username+"。恭喜您成为本站的第 "+userRes.data.numAll+" 位用户!"
                }
                this.$http.post("/msg/sendMsg",msg)
              }

              window.open('login','_self')
            })
          }
        }
      },
      async sendVerifyCode(){
        console.log(this.ruleForm.phone)
        if((/^1[3-9]\d{9}$/.test(this.ruleForm.phone))){
          const {data: res} = await this.$http.get(`/user/getVerifyCode/${this.verifyInfo.phone}`)
          if (res.status != 200) return this.$message.error('验证码发送失败!');
          else {
            this.verifyCodeBack = res.data
            this.$message.success("验证码发送成功!")
          }
          console.log(res.data)
        }
        else{
          this.$message.error('手机号错误!')
        }
      }
    },
  }
</script>

<style scoped>
  .login-container {
    width: 100%;
    height: 100%;
  }

  .login-page {
    -webkit-border-radius: 5px;
    border-radius: 5px;
    margin: 180px auto;
    width: 350px;
    padding: 35px 35px 15px;
    background: #fff;
    border: 1px solid #eaeaea;
    box-shadow: 0 0 25px #cac6c6;
  }

  .el-row {
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .el-col {
    border-radius: 4px;
  }

  .bg-purple-dark {
    background: #99a9bf;
  }

  .bg-purple {
    background: #d3dce6;
  }

  .bg-purple-light {
    background: #e5e9f2;
  }

  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }

  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }

  label.el-checkbox.rememberme {
    margin: 0px 0px 15px;
    text-align: left;
  }
</style>
